package com.example.service;

import com.example.entity.Clazz;
import com.example.entity.Student;
import com.example.entity.Teacher;
import com.example.entity.User;
import com.example.exception.CustomException;
import com.example.mapper.StudentMapper;
import com.example.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class StudentService {
    @Resource
    private StudentMapper studentMapper;
    @Resource
    private UserMapper userMapper;


    public PageInfo<Student> selectPage(Student student, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Student> list = studentMapper.selectAll(student);
        return PageInfo.of(list);
    }

    public void addStudent(Student student) {
        // 1. 插入用户表（User）
        if (studentMapper.countByNumber(student.getStudentNumber()) > 0 ) {
            throw new CustomException("400","学号已存在");
        }
        User user = new User();
        user.setUsername(student.getStudentName()+student.getStudentNumber());
        user.setUserRole("student");
        user.setPassword("123456");
        userMapper.insert(user);
        // 2. 插入学生表
        student.setStudentId(user.getUserId());       // 老师ID = 用户ID
        studentMapper.insert(student);
    }
    public void updateStudent(Student student) {
        Student exstingstudent = studentMapper.selectById(student.getStudentId());
        if (exstingstudent.getStudentNumber().equals(student.getStudentNumber())){
            if (exstingstudent.getStudentName().equals(student.getStudentName()) && exstingstudent.getClassId().equals(student.getClassId())){
                return;
            }
        } else {
            if (studentMapper.countByNumber(student.getStudentNumber()) > 0 ) {
                throw new CustomException("400","学号已存在");
            }
        }
        // 同时修改用户的昵称
        User user = new User();
        user.setUserId(student.getStudentId());
        user.setUsername(student.getStudentName()+student.getStudentNumber());
        userMapper.update(user);

        studentMapper.update(student);
    }

    public void deleteStudent(Integer studentId) {
        studentMapper.delete(studentId);
        userMapper.delete(studentId);
    }

    public void deleteBatch(List<Integer> ids) {
        for (Integer studentId : ids) {
            studentMapper.delete(studentId);
            userMapper.delete(studentId);
        }
    }
}
